/*
 * Copyright (C) 2010-2011 sunjumper@163.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package mf.mfrpc.http;

import java.io.IOException;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Http工具类。
 */
public class HttpUtil {

    private static final Logger LOG = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * cookie存储策略
     */
    public static final CookiePolicy ACCEPT_ORIGINAL_SERVER = new CookiePolicy() {

        @Override
        public boolean shouldAccept(URI uri, HttpCookie cookie) {
            String host = uri.getHost();
            String domain = cookie.getDomain();
            if ("localhost".equalsIgnoreCase(host) && "localhost".equals(domain)) {
                return true;
            }
            return HttpCookie.domainMatches(domain, host);
        }
    };

    /** 默认的cookie内存存储管理 */
    private static final CookieManager CookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);

    /**
     * 获取cookie存储管理。
     */
    public static CookieManager getCookieManager() {
        return CookieManager;
    }

    /**
     * 存储http请求的cookie。
     */
    public static void storeCookies(HttpURLConnection con) throws CookieException {
        try {
            CookieManager.put(con.getURL().toURI(), con.getHeaderFields());
        } catch (IOException e) {
            throw new CookieException(e);
        } catch (URISyntaxException e) {
            throw new CookieException(e);
        }
    }

    /**
     * 从cookie存储中设置http请求的cookie。
     */
    public static void setCookies(HttpURLConnection con) throws CookieException {
        List<String> cookies = null;
        try {
            cookies = CookieManager.get(con.getURL().toURI(), Collections.EMPTY_MAP).get(HttpConstants.REQUEST_COOKIE_HEADER);
        } catch (IOException e) {
            throw new CookieException(e);
        } catch (URISyntaxException e) {
            throw new CookieException(e);
        }
        StringBuilder str = new StringBuilder();
        if (cookies != null && !cookies.isEmpty()) {
            int length = cookies.size();
            for (int i = 0; i < length - 1; i++) {
                str.append(cookies.get(i)).append(';');
            }
            str.append(cookies.get(length - 1));
            LOG.debug("set {} cookies : [{}]", con.getURL(), str.toString());
            con.setRequestProperty(HttpConstants.REQUEST_COOKIE_HEADER, str.toString());
        }
    }

    /**
     * 获取传输类型。
     */
    public static TransferType getTransferType(HttpURLConnection con) {
        String tt = con.getHeaderField(HttpConstants.RESPONSE_TRANSFERTYPE_HEADER);
        return tt == null ? null : TransferType.valueOf(tt);
    }
}
